<template>
  <div id="app">
    <div id="map"></div>
    <Icon :data="data" ref="icon"></Icon>
    <div class="nav">
      新冠疫情时空传播过程可视化模拟
      <span   v-show="uploadShow" style="color: #fff; font-size: 15px; margin-left: 750px"
        >数据来源:{{ uploadName == "" ? "无" : uploadName }}</span
      >


      <el-upload
        v-show="uploadShow"
        class="upload-demo"
        action="http"
        :http-request="Upload"
        :before-upload="beforeUpload"
        :show-file-list="false"
      >
        <el-button size="small" type="primary">上传区域</el-button>
      </el-upload>

      <el-switch
      class="isfix"
        v-model="model"
        @change="switchChange"
        active-text="随机模式"
        inactive-text="固定模式"
      >
      </el-switch>
      <BtImg
        @end="endClick"
        @stop="stopClick"
        @resume="resumeClick"
        @openTimer="openTimer"
        @reload="reload"
      ></BtImg>
    </div>

    <el-drawer
      :visible.sync="drawer"
      size="35%"
      :modal="false"
      :show-close="false"
      ref="sda"
      :wrapperClosable="false"
    >
      <Echarts
        :echartsData="echartsData"
        ref="echart"
        :newEchartsData="newEchartsData"
      ></Echarts>
    </el-drawer>
    <el-button
      style="position: absolute; top: 360px; right: -72px"
      @click="echartsBtnClick"
    >
      疫情数据可视化</el-button
    >
  </div>
</template>
<script>
import { Mapbox } from "@antv/l7-maps";
import { Scene, PointLayer, PolygonLayer, Popup, LineLayer } from "@antv/l7";
import Icon from "./views/Icon.vue";
import BtImg from "../src/views/BtImg.vue";
import data from "./assets/qiaokobuilding.js";
import data1 from "./assets/qiaokoroads.js";
import Vue from "vue";
import {
  sendMessageInitData,
  resumeRunAgent,
  stopAgent,
  endAgent,
  startAgent,
  reLoadAgent,
} from "../src/network/network.js";
import Echarts from "./views/Echarts.vue";
import Toast from "./components/Toast/Toast.vue";
import * as turf from "@turf/turf";
import { Upload } from "element-ui";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    Icon,
    BtImg,
    Echarts,
    Toast,
  },
  props: {},
  data() {
    //这里存放数据
    return {
      scene: {},
      layer: {},
      popup: {},
      pointLayer: null,
      index: 1,
      data: {},
      nowData: {},
      timer: {},
      thisA: 0,
      drawer: false,
      echartsData: [["agentNumber", "datetime", "unit", "agentType", "nums"]],
      isStart: false,
      lineLayer: {},
      squareLayer: {},
      newEchartsData: [
        ["agentNumber", "datetime", "unit", "agentType", "nums"],
      ],
      model: false,
      uploadName: "",
      isloop:false
    };
  },
  watch: {
    //开启第一次的接口调用
    // isStart: {
    //   handler(newV, oldV) {
    //     if (newV) {
    //       this.openTimer();
    //     }
    //   },
    // },
  },
  methods: {
    //改变层级改变圆圈大小的函数
    changeIndex() {
      this.index = parseInt(this.scene.getZoom());
      if (this.pointLayer) {
        this.pointLayer.size(this.index - 7);
      }
      this.scene.render();
    },
    //暂停的函数
    stopClick() {
      stopAgent();
      window.clearInterval(this.timer);
    },
    //恢复的函数
    resumeClick() {
      resumeRunAgent();
      if (window.localStorage.getItem("isClick")) {
        this.openTimer();
      }
    },
    //发送请求
    postData() {
      fetch("/api2", {
        headers: {
          "Cache-Control": "no-cache",
        },
      })
        .then((res) => res.json())
        .then((data) => {
          //添加echarts数据
          console.log(data);
          if (this.thisA < 20000) {
            this.thisA++;
            // console.log(data);
            let {
              AsymptomaticAgentCount,
              agent,
              datetime,
              infectedagentCount,
              unit,
              stepflag,
              // 潜伏期
              infectedagentLatentCount,
              //发病期
              infectedagentOnsetCount,
              //重症期
              infectedagentSevereCount,
              //死亡人数
              DeathNumber,
            } = data;

            //判断是否结束
            if (!stepflag) {
              new Vue().$toast.show("演示结束了");
              window.clearInterval(this.timer);
              return;
            }
            agent = agent < 0 ? -agent : agent;
            infectedagentCount =
              infectedagentCount < 0 ? -infectedagentCount : infectedagentCount;
            AsymptomaticAgentCount =
              AsymptomaticAgentCount < 0
                ? -AsymptomaticAgentCount
                : AsymptomaticAgentCount;
            DeathNumber = DeathNumber < 0 ? -DeathNumber : DeathNumber;
            this.echartsData.push([agent, datetime, unit, "健康", this.thisA]);
            this.echartsData.push([
              AsymptomaticAgentCount,
              datetime,
              unit,
              "无症状",
              this.thisA,
            ]);
            this.echartsData.push([
              DeathNumber,
              datetime,
              unit,
              "死亡人数",
              this.thisA,
            ]);
            this.echartsData.push([
              infectedagentCount,
              datetime,
              unit,
              "感染",
              this.thisA,
            ]);

            this.newEchartsData.push([
              infectedagentLatentCount,
              datetime,
              unit,
              "潜伏期",
              this.thisA,
            ]);
            this.newEchartsData.push([
              infectedagentOnsetCount,
              datetime,
              unit,
              "发病期",
              this.thisA,
            ]);
            this.newEchartsData.push([
              infectedagentSevereCount,
              datetime,
              unit,
              "重症期",
              this.thisA,
            ]);
            this.newEchartsData.push([
              agent,
              datetime,
              unit,
              "健康人数",
              this.thisA,
            ]);
            this.newEchartsData.push([
              DeathNumber,
              datetime,
              unit,
              "死亡人数",
              this.thisA,
            ]);
          }

          // console.log(this.echartsData);
          // console.log(this.newEchartsData);

          if (window.localStorage.getItem("isClick")) {
            this.data = data;
            this.nowData = data.geojsonList;
          } else {
            this.nowData = null;
            this.data = null;
            this.echartsData = [
              ["agentNumber", "datetime", "unit", "agentType", "nums"],
            ];
            this.newEchartsData = [
              ["agentNumber", "datetime", "unit", "agentType", "nums"],
            ];
          }

          // this.nowData = data.geojsonList;
          if (!this.pointLayer) {
            this.pointLayer = new PointLayer({
              zIndex: 111,
            })
              .source(this.nowData, {
                parser: {
                  type: "json",
                  x: "lng",
                  y: "lat",
                },
              })
              .shape("circle")
              .size(this.index - 7)
              .color("agentType", (value) => {
                if (value === "AsymptomaticAgent") {
                  return "yellow";
                }
                if (value === "InfectedAgent") {
                  return "red";
                }
                if (value === "NormalAgent") {
                  return "blue";
                }
              });

            this.scene.addLayer(this.pointLayer);
          } else {
            this.pointLayer.setData(this.nowData);
          }

          this.pointLayer.on("click", (e) => {
            const { lng, lat } = e.lngLat;
            this.popup = new Popup({
              offsets: [0, 50],
              closeButton: false,
            });
            this.popup.setLnglat({
              lng,
              lat,
            });
            let masks, vaccine, agentType, speed;

            if (e.feature.agentType === "AsymptomaticAgent") {
              agentType = "无症状";
            }
            if (e.feature.agentType === "InfectedAgent") {
              agentType = "感染";
            }
            if (e.feature.agentType === "NormalAgent") {
              agentType = "健康";
            }

            if (e.feature.masks == "false") {
              masks = "否";
            } else {
              masks = "是";
            }

            if (e.feature.vaccine == "false") {
              vaccine = "否";
            } else {
              vaccine = "是";
            }
            speed = e.feature.speed;
            this.popup.setHTML(
              `<span>此智能体的信息为</span>:<br>
              <table border="1" style="border-spacing:0px;">
        <tr>
            <td style="padding:5px;">id</td>
            <td style="padding:5px;">${e.feature.id}</td>
        </tr>
        <tr>
            <td style="padding:5px;">人群类型</td>
            <td style="padding:5px;">${agentType}</td>
        </tr>
        <tr>
            <td style="padding:5px;">是否戴口罩</td>
            <td style="padding:5px;">${masks}</td>
        </tr>
        <tr>
            <td style="padding:5px;">是否接种疫苗</td>
            <td style="padding:5px;">${vaccine}</td>
        </tr>
        <tr>
            <td style="padding:5px;">速度</td>
            <td style="padding:5px;">${speed}</td>
        </tr>
    </table>`
              // `<span>此用户的基本信息为</span>:<br>id: ${e.feature.id}<br>人群类型：${e.feature.agentType}<br>是否戴口罩：${masks}<br>是否接种疫苗：${vaccine}`
            );
            this.scene.addPopup(this.popup);
          });
        });
    },
    //控制echarts按钮的点击
    echartsBtnClick() {
      var drawerLayer =
        document.getElementsByClassName("el-drawer__wrapper")[0];
      var childeldrawer = document.getElementsByClassName("el-drawer")[0];
      drawerLayer.style.visibility = "hidden";
      childeldrawer.style.visibility = "visible";
      this.drawer = !this.drawer;
      if (!this.$refs.sda.$children[0]) return;
      this.$refs.sda.$children[0].rend();
    },
    //开启定时器函数
    openTimer() {
      // window.clearInterval(this.timer);
      // this.timer = null;
      // this.timer = setInterval(() => {
      //   if (this.isStart) {
      //     this.postData();
      //   }

      //   this.$refs.sda.$children[0] && this.$refs.sda.$children[0].rend();
      //   // if( this.$refs.sda.$children[0] ){
      //   //   this.$refs.sda.$children[0].toggleIndex=false;
      //   // }
      // }, 800);

      window.clearInterval(this.timer);
      this.timer = null;
      this.timer = setInterval(() => {
        if (window.localStorage.getItem("isClick")) {
          this.postData();
        }

        this.$refs.sda.$children[0] && this.$refs.sda.$children[0].rend();
        // if( this.$refs.sda.$children[0] ){
        //   this.$refs.sda.$children[0].toggleIndex=false;
        // }
      }, 800);
    },
    //重置的函数
    reload() {
      // this.isStart = false;
      window.localStorage.setItem("isClick", "");
      window.clearInterval(this.timer);
      if (this.pointLayer) {
        this.pointLayer.setData(null);
      }

      this.nowData = {};

      this.echartsData = [
        ["agentNumber", "datetime", "unit", "agentType", "nums"],
      ];
      this.newEchartsData = [
        ["agentNumber", "datetime", "unit", "agentType", "nums"],
      ];
      // this.$refs.sda.$children[0].rend();
      this.thisA = 0;
    },
    //结束的函数
    endClick() {
      // this.isStart = false;
      window.localStorage.setItem("isClick", "");
      window.clearInterval(this.timer);
      this.timer = null;
      if (this.pointLayer) {
        this.pointLayer.setData(null);
      }

      this.nowData = {};
      this.data = {};
      this.echartsData = [
        ["agentNumber", "datetime", "unit", "agentType", "nums"],
      ];
      this.newEchartsData = [
        ["agentNumber", "datetime", "unit", "agentType", "nums"],
      ];

      this.$refs.sda.$children[0] && this.$refs.sda.$children[0].clear();
      if (this.$refs.sda.$children[0]) {
        this.$refs.sda.$children[0].toggleIndex = false;
      }
      if (this.$refs.icon) {
        this.$refs.icon.step = "1h";
      }
    },
    //模式切换
    switchChange(val) {
      this.uploadShow = val;
      //随机模式
      if (val) {
     
      } //固定模式
      else {
      }
    },
    //文件上传
    Upload(file) {
      const formdata = new FormData();
      formdata.append("file", file.file);
      formdata.append("Content-Type", "multipart/form-data");
      console.log(file);
      this.uploadName = file.file.name;
    },
    // 上传前的大小验证及格式验证
    beforeUpload(file) {
      const isJPG = file.name.slice(-5) === ".json";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$toast.show("上传文件只能是 Json 格式");
      }
      if (!isLt2M) {
        this.$toast.show("上传文件大小不能超过 2MB");
      }
      return isJPG && isLt2M;
    },
  },

  created() {},

  mounted() {
    const map = new Mapbox({
      style: "mapbox://styles/mapbox/streets-v11", // 样式URL
      center: [114.255, 30.5755],
      pitch: 0,
      zoom: 16,
      token:
        "pk.eyJ1IjoiY2luZHkwNzkiLCJhIjoiY2p5MW0yM2FmMDNhbzNpcnpoeGVqOXpmYSJ9.zKbdCDdA69t7b3zSWctaRw",
    });

    this.scene = new Scene({
      id: "map",
      map,
    });

    // this.scene.addSource("gridsource", {
    //   type: "geojson",
    //   data: gird,
    // });
    // this.scene.addLayer({
    //   id: "gridlayer",
    //   type: "fill",
    //   source: "gridsource",
    //   paint: {
    //     "fill-color": "#486DE0",
    //     "fill-outline-color": "ffffff",
    //   },
    // });
    var bbox = [100, 17, 90, 20];
    var cellSide = 5;
    var options = { units: "miles" };
    const gird = turf.squareGrid(bbox, cellSide, options);
    console.log(this.scene.getBounds());
    console.log(gird);
    this.squareLayer = new LineLayer({
      zIndex: 4,
    })
      .source(gird)
      .shape("line")
      .color("red");

    this.scene.addImage("00", "http://111.47.28.118:8090/repast/asAgent.svg");

    //面图层
    this.layer = new PolygonLayer({
      zIndex: 2,
    })
      .source(data)
      .shape("fill")
      .size("Name", [100, 120, 160, 200, 260, 500])
      .color("Name", [
        "#b29985",
        "#b29985",
        "#b29985",
        "#b29985",
        "#b29985",
        "#b29985",
        "#b29985",
      ])
      .select({
        color: "#9fbbd7",
      });

    this.lineLayer = new LineLayer({
      zIndex: 3,
    })
      .source(data1)
      .size(4)
      .shape("line")
      .color("#fff")
      .style({
        borderWidth: 0.4,
        borderColor: "#fff",
      });

    //地图有变化便回调的函数
    this.scene.on("loaded", () => {
      this.scene.addLayer(this.layer);
      this.scene.addLayer(this.lineLayer);
      this.scene.addLayer(this.squareLayer);

      //只有点击初始化才能开启定时器

      if (window.localStorage.getItem("isClick")) {
        this.openTimer();
      }

      this.layer.on("click", (e) => {
        this.layer.setActive(e.featureId);
        const { lng, lat } = e.lngLat;
        this.popup = new Popup({
          offsets: [0, 50],
          closeButton: false,
        });
        this.popup.setLnglat({
          lng,
          lat,
        });
        this.popup.setHTML(
          `<span>房屋的信息为</span>:<br>id: ${e.feature.properties.ID}`
        );

        this.scene.addPopup(this.popup);
      });

      this.layer.on("dblclick", (e) => {
        this.layer.setActive(-1);
      });

      this.lineLayer.on("click", (e) => {
        this.lineLayer.setActive(e.featureId);
        const { lng, lat } = e.lngLat;
        this.popup = new Popup({
          offsets: [0, 50],
          closeButton: false,
        });
        this.popup.setLnglat({
          lng,
          lat,
        });
        this.popup.setHTML(
          `<span>道路的信息为</span>:<br>id: ${e.feature.properties.ID}`
        );

        this.scene.addPopup(this.popup);
      });

      this.lineLayer.on("dblclick", (e) => {
        this.lineLayer.setActive(-1);
      });
    });

    //根据层级大小显示不同节点大小
    this.scene.on("zoomend", (e) => {
      this.changeIndex();
    });

    //为建筑物添加popup
    // this.layer.on("mousemove", (e) => {
    //   this.layer.setActive(e.featureId);
    //   const { lng, lat } = e.lngLat;
    //   this.popup = new Popup({
    //     offsets: [0, 50],
    //     closeButton: false,
    //   });
    //   this.popup.setLnglat({
    //     lng,
    //     lat,
    //   });
    //   this.popup.setHTML(
    //     `<span>房屋的信息为</span>:<br>id: ${e.feature.properties.ID}`
    //   );

    //   this.scene.addPopup(this.popup);
    // });
  },
};
</script>
<style scoped lang="less">
@import url("./assets/css/normalize.css");
body {
  padding: 0;
  margin: 0;
}
#app {
  height: 100%;
}

#app #map {
  height: 100%;
  width: 100%;
  position: fixed;
}

.title {
  position: absolute;
  top: 0;
  left: 50%;
  width: 700px;
  height: 100px;
  font-size: 20px;
  color: #fff;
  transform: translateX(-50%);
  text-align: center;
  line-height: 100px;
  /* #BED9F3 */
  text-shadow: 0 0 5px #53bbee, 0 0 10px #53bbee, 0 0 15px #53bbee;

  font-size: 80px;
  font-family: "Courier New", Courier, monospace;
  z-index: 666;
  /* opacity: 0.7; */
}
/deep/ .l7-popup .l7-popup-content {
  padding: 5px !important;
}
/deep/ .el-drawer.rtl {
  height: 400px;
  top: 200px;
}
.el-button {
  transform: rotate(90deg);
  z-index: 9999;
  padding: 10px 40px;
}
.el-drawer__wrapper {
  visibility: visible;
}

.isfix {
  left: 700px;
  top: 50%;
  transform: translateY(-50%);
  position: absolute;
  color: #fff;
}

/deep/ .el-switch__label.is-active {
  color: red;
}


.el-drawer {
  visibility: visible;
}
.nav {
  position: absolute;
  top: 0px;
  left: 0;
  width: 100%;
  z-index: 99;
  background-color: black;
  background-image: linear-gradient(#0e0d0d, #7b7382);
  height: 70px;
  color: #fff;
  font-size: 37px;
  line-height: 70px;
  padding: 0 40px;
  box-sizing: border-box;
  z-index: 9999;
}
/deep/ .el-drawer__header {
  margin: 0;
}
/deep/ .el-drawer__body {
  box-sizing: border-box;
  padding: 0;
  margin-left: 20px;
}
/deep/ .el-button {
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3);
}
/deep/ .el-switch__label * {
  font-size: 17px;
}
/deep/ .el-switch__label {
  color: #fff;
}
/deep/ .el-button:focus,
.el-button:hover {
  background-color: rgba(0, 0, 0, 0.3);
  color: #fff;
}

/deep/ .el-drawer__body {
  padding-left: 20px;
  margin-left: 0;
  position: relative;
  box-sizing: border-box;
}
/deep/ .el-button--primary {
  border-color: #fff;
}
.upload-demo {
  position: absolute;
  top: 40%;
  transform: translateY(-50%);
  right: 500px;

  .el-button {
    transform: rotate(0deg);
  }
}
// /deep/ .el-drawer__wrapper{
//   z-index: 20 !important;
// }\
@import url("../src/assets/css/normalize.css");
</style>
